package ftp

import (
	"fmt"
	"gin/model"
	"strconv"
	"strings"
	"time"
	"unicode/utf8"
)

// 解析聊天日志
func (p *DataParsing) parsingChatLog(catData []string, ftpInfoId int64, useIndex model.DataIndex) []model.DataChat {

	var catDate, catLogTime, catSteamId, catName, catGameId, catType, catContent string
	var end int
	var dataChatArr []model.DataChat
	for _, cat := range catData {
		//fmt.Println("原始数据", cat)
		catContent = ""
		parts := strings.Split(cat, ":")
		//fmt.Println("分割数据", parts)
		timeParts := strings.Split(parts[0], "-")
		//fmt.Println("分割数据2", timeParts)
		//日期转换  年-月-日
		catDate = strings.Replace(timeParts[0], ".", "-", -1)
		//fmt.Println("转换数据1", catDate)
		//时间转换  时:分:秒
		catTime := strings.Replace(timeParts[1], ".", ":", -1)
		//fmt.Println("转换数据2", catTime)
		layout := "2006-01-02 15:04:05"
		// 解析时间字符串
		//fmt.Println("解析时间格式为", catDate+" "+catTime)
		t, err := time.Parse(layout, catDate+" "+catTime)
		if err != nil {
			fmt.Println("解析时间格式为", err.Error())
			catLogTime = "0"
			//return
		}
		// 转换为 Unix 时间戳（秒）

		catLogTime = strconv.FormatInt(t.Unix(), 10)
		logTime, _ := strconv.ParseInt(catLogTime, 10, 64)
		//太平洋时间制  + 8 小时
		//logTime = logTime + 3600*8
		t = time.Unix(logTime, 0)
		catDate = t.Format("2006-01-02")

		hour, minute, second := t.Clock()
		catTime = fmt.Sprintf("%02d:%02d:%02d", hour, minute, second)
		//
		//Steamed 获取
		// 查找第一个单引号的位置
		start := strings.Index(cat, "'")
		if start < 0 {
			catSteamId = ""
		} else {
			// 查找第二个单引号的位置
			end := strings.Index(cat[start+1:], "'")
			if end < 0 {
				catSteamId = ""
			} else {
				// 提取引号内的数据
				data := cat[start+1 : start+1+end]
				parts = strings.Split(data, ":")
				catSteamId = parts[0]
			}
		}

		// 游戏id获取
		index := strings.Index(parts[1], "(")
		if index < 0 {
			//fmt.Println("找不到 '('")
			catName = ""
		} else {
			catName = parts[1][:index]

			catName = TruncateStringByCharCount(catName, 50)

			// 输出字节集（以十六进制表示）
			//fmt.Printf("Byte slice: %x\n", byteSlice)

			// 将字节集转换回字符串
			catName = filterInvalidChars(catName)
		}

		//游戏id获取
		start = strings.Index(cat, "(")
		if start < 0 {
			catGameId = "-1"
			//fmt.Println("找不到单引号")
			//return
		} else {
			// 查找第二个单引号的位置
			end = strings.Index(cat[start+1:], ")")
			if end < 0 {
				catGameId = "-1"
				//fmt.Println("找不到第二个单引号")
				//return
			} else {
				// 提取引号内的数据
				catGameId = cat[start+1 : start+1+end]
			}
		}

		// 聊天类型获取
		start = strings.Index(cat, ")' '")
		if start < 0 {
			catType = "0"
		} else {
			// 查找第二个单引号的位置
			end = strings.Index(cat[start+4:], ":")
			if end < 0 {
				catType = "0"
			} else {
				catType = cat[start+4 : start+4+end]
			}
		}
		//fmt.Println("类型为:", catType)

		//聊天内容获取
		start = strings.LastIndex(cat, ": ")
		if start < 0 {
			catContent = ""
		} else {
			end = strings.LastIndex(cat, "'")
			catContent = cat[start+2 : end]

			catContent = TruncateStringByCharCount(catContent, 200)

			// 输出字节集（以十六进制表示）
			//fmt.Printf("Byte slice: %x\n", byteSlice)

			// 将字节集转换回字符串
			catContent = filterInvalidChars(catContent)

		}
		//fmt.Println("数据为：", convertedString)
		//fmt.Println("数据为：",catDate, catLogTime, catSteamId, catName, catGameId, catType, catContent)

		gameId, _ := strconv.ParseInt(catGameId, 10, 64)
		downloadFile := model.DataChat{FtpInfoId: ftpInfoId, Date: catDate, Time: catTime, LogTime: logTime, SteamId: catSteamId, GameName: catName, GameId: gameId, CatType: catType, Content: catContent}
		dataChatArr = append(dataChatArr, downloadFile)
	}
	return dataChatArr
}

func TruncateStringByCharCount(s string, n int) string {
	// 如果字符串长度小于或等于 n，则直接返回整个字符串
	if utf8.RuneCountInString(s) <= n {
		return s
	}

	// 创建一个 builder 来构建结果字符串
	var result strings.Builder
	var charCount int

	// 遍历字符串中的每个 rune（字符）
	for _, runeValue := range s {
		// 将 rune 添加到 builder 中
		result.WriteRune(runeValue)
		// 增加字符计数器
		charCount++
		// 检查是否已经添加了 n 个字符
		if charCount == n {
			break
		}
	}

	// 将 builder 转换为字符串并返回
	return result.String()
}

// 过滤乱码
func filterInvalidChars(text string) string {
	var result []rune
	for _, r := range text {
		if r >= 0x20 && r <= 0x7E || r >= 0x80 {
			result = append(result, r)
		}
	}
	return string(result)
}
